//
//  FoodDetailViewController.m
//  FoodList
//
//  Created by lanou on 16/4/8.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "FoodDetailViewController.h"
#import "RequestManger.h"
#import "FoodDetailModel.h"
#import <UIImageView+WebCache.h>
#import "FoodDetaiTableViewCell.h"
#import "FoodDetailTableViewCell2.h"
#import "ImageViewCellTableViewCell.h"

@interface FoodDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UIImageView *topImageView;
@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *modelArray1;// 选购窍门
@property(nonatomic,strong)NSMutableArray *modelArray2;// 营养价值
@property(nonatomic,strong)NSMutableArray *modelArray3;//食用描述

@property(nonatomic,strong)NSMutableArray *titleArray;// 装分区标题

@property(nonatomic,strong)UILabel *titleLabel;// 分区标题

@property(nonatomic,strong)FoodDetailModel *model;

@property(nonatomic,assign)CGSize size;

@property(nonatomic,strong)UIButton *backButton;// 自定义导航单返回按钮
@property(nonatomic,strong)UIButton *back;

@property(nonatomic,assign)NSInteger hh1;
@property(nonatomic,assign)NSInteger hh2;

@end

@implementation FoodDetailViewController
#pragma mark ----- 数据解析 ------
-(void)request
{
    //NSLog(@"~~~~~~~~~~~~ %@  %@",_idStr,_titleStr);
    
    NSDictionary *parDic = @{@"id":_idStr,@"title":[_titleStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]};
    [RequestManger requestWithURL:@"http://api.meishi.cc/v5/shicai_detail2.php?format=json" requestType:@"RequestPOST" parDic:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //NSLog(@"%@",dic);
        _model = [[FoodDetailModel alloc]init];
        [_model setValuesForKeysWithDictionary:dic];
        
        NSArray *objArray = dic[@"obj"];
        _titleArray = [NSMutableArray array];
        _modelArray1 = [NSMutableArray array];
        _modelArray2 = [NSMutableArray array];
        _modelArray3 = [NSMutableArray array];
        for (NSDictionary *objDic in objArray) {
            NSString *title = objDic[@"title"];
            [_titleArray addObject:title];
            if (objDic == objArray[0]) {
                NSArray *array = objDic[@"content"];
                for (NSDictionary *cellDic in array) {
                    [_model setValuesForKeysWithDictionary:cellDic];
                    [_modelArray1 addObject:_model.desc];
                }
            }
            if (objDic == objArray[1]){
                NSArray *array = objDic[@"content"];
                for (NSDictionary *cellDic in array) {
                    [_model setValuesForKeysWithDictionary:cellDic];
                    [_modelArray2 addObject:_model.desc];
                   // NSLog(@"modelArray2 = %@",_model.desc);
                }
            }
            if (objDic == objArray[2]) {
                NSArray *array = objDic[@"content"];
                for (NSDictionary *cellDic in array) {
                    [_model setValuesForKeysWithDictionary:cellDic];
                    [_modelArray3 addObject:_model.desc];
                }
            }
        }
        [self addView];
        [_topImageView sd_setImageWithURL:[NSURL URLWithString:_model.img]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.view addSubview:_back];
        });
    } error:^(NSError *error) {
        NSLog(@"请求错误");
    }];
}
#pragma mark --------------- viewDidLoad ----------------------
- (void)viewDidLoad {
    [super viewDidLoad];
    [self request];
    self.navigationItem.title = _titleStr;
    
    _backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _backButton.frame = CGRectMake(10, 20, 18, 20);
    [_backButton setImage:[UIImage imageNamed:@"bac"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithCustomView:_backButton];
    self.navigationItem.leftBarButtonItem = left;
   // NSLog(@"%f    %f",left.accessibilityFrame.size.width, left.accessibilityFrame.size.height);
    
    _back = [UIButton buttonWithType:UIButtonTypeSystem];
    _back.frame = CGRectMake(10, 20, 18, 20);
    [_back setImage:[UIImage imageNamed:@"bac"] forState:UIControlStateNormal];
    [_back addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];

}
-(void)back:(UIButton *)button{
    self.navigationController.navigationBar.alpha = 1;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.alpha = 0;
}

-(void)addView
{
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
    [self.view addSubview:_tableView];
    
    _topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -200, Width, 200)];
    _topImageView.contentMode = UIViewContentModeScaleAspectFill;
    [_tableView addSubview:_topImageView];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 图片下拉放大
    CGFloat y = scrollView.contentOffset.y;
    if (y < -200) {
        CGRect frame = _topImageView.frame;
        frame.origin.y = y;
        frame.size.height = -y;
        _topImageView.frame = frame;
    }
    // 上拉 导航栏颜色渐变
    float h = y / 200;
    if (y < 200) {
        self.navigationController.navigationBar.alpha = h;
    }else{
        self.navigationController.navigationBar.alpha = 1;
    }
}
#pragma mark ----------------------- tableView -------------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _titleArray.count + 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }if (section == 1) {
        return _modelArray1.count;
    }if (section == 2) {
        return _modelArray2.count;
    }else  {
        return _modelArray3.count;
    }
}
// 设置标题头部宽度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
// 设置分区的标题
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Width, 50)];
    _titleLabel.backgroundColor = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    if (section == 0) {
        _titleLabel.text = nil;
    }
    if (section == 1) {
        _titleLabel.text = _titleArray[0];
    }if (section == 2){
        _titleLabel.text = _titleArray[1];
    }if (section == 3){
        _titleLabel.text = _titleArray[2];
    }
    return _titleLabel;
}
// 返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableView.separatorStyle = UITableViewScrollPositionNone;
    if (indexPath.section == 0) {
        FoodDetailTableViewCell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (cell2 == nil) {
            cell2 = [[NSBundle mainBundle]loadNibNamed:@"FoodDetailTableViewCell2" owner:nil options:nil].firstObject;
        }
        cell2.heatLabel.text = _heatStr;
        if ([cell2.heatLabel.text isEqualToString:@"较低热量"]) {
            cell2.heatLabel.textColor = [UIColor greenColor];
        }else if ([cell2.heatLabel.text isEqualToString:@"较高热量"]){
            cell2.heatLabel.textColor = [UIColor redColor];
        }else
        {
            cell2.heatLabel.textColor = [UIColor yellowColor];
        }
        cell2.gongxiao1label.text = _gongxiaoArray[0];
        cell2.gongxiao3label.text = _gongxiaoArray[1];
        cell2.titleLabel.text = _titleStr;
        return cell2;
    }else{
        
        FoodDetaiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"foodDetail"];
        if (cell == nil) {
                        cell = [[NSBundle mainBundle] loadNibNamed:@"FoodDetaiTableViewCell" owner:nil options:nil].firstObject;
        }
        if (indexPath.section == 1) {
            cell.descLabel.text = _modelArray1[indexPath.row];
            if ([[cell.descLabel.text substringToIndex:7] isEqualToString:@"http://"]) {
                ImageViewCellTableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"imageCell"];
                if (imageCell == nil) {
                    imageCell = [[NSBundle mainBundle] loadNibNamed:@"ImageViewCellTableViewCell" owner:nil options:nil].firstObject;
                }
                [imageCell.imageViewCell sd_setImageWithURL:[NSURL URLWithString:cell.descLabel.text]];
                return imageCell;
            }
        }if (indexPath.section == 2) {
            cell.descLabel.text = _modelArray2[indexPath.row];
        }if (indexPath.section == 3) {
            cell.descLabel.text = _modelArray3[indexPath.row];
            if ([[cell.descLabel.text substringToIndex:7] isEqualToString:@"http://"]) {
                ImageViewCellTableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"imageCell"];
                if (imageCell == nil) {
                    imageCell = [[NSBundle mainBundle] loadNibNamed:@"ImageViewCellTableViewCell" owner:nil options:nil].firstObject;
                }
                [imageCell.imageViewCell sd_setImageWithURL:[NSURL URLWithString:cell.descLabel.text]];
                return imageCell;
            }
        }
        return cell;
    }
}

// 返回cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        FoodDetailTableViewCell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (cell2 == nil) {
            cell2 = [[NSBundle mainBundle]loadNibNamed:@"FoodDetailTableViewCell2" owner:nil options:nil].firstObject;
        }
        return 120;
    }else{
        FoodDetaiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"foodDetail"];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FoodDetaiTableViewCell" owner:nil options:nil];
            for (id oneObject in nib) {
                if ([oneObject isKindOfClass:[FoodDetaiTableViewCell class]]) {
                    cell = (FoodDetaiTableViewCell *)oneObject;
                }
            }
            if (indexPath.section == 1) {
                if ([[_modelArray1[indexPath.row] substringToIndex:7] isEqualToString:@"http://"]) {
//                    ImageViewCellTableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"imageCell"];
//                    if (imageCell == nil) {
//                        imageCell = [[NSBundle mainBundle] loadNibNamed:@"ImageViewCellTableViewCell" owner:nil options:nil].firstObject;
//                    }
//                    float scale = (Width - 20) / _model.width;
                    return 210;
                }else{
                    [cell cellHeight:[self.modelArray1 objectAtIndex:indexPath.row]];
                }
            }if (indexPath.section == 2) {
                [cell cellHeight:[self.modelArray2 objectAtIndex:indexPath.row]];
            }if (indexPath.section == 3) {
                if ([[_modelArray3[indexPath.row] substringToIndex:7] isEqualToString:@"http://"]) {
                    return 100;
                }else{
                    [cell cellHeight:[self.modelArray3 objectAtIndex:indexPath.row]];
                }
            }
            _size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingExpandedSize];
        }
        return _size.height + 1;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
